// 设置 STOMP 客户端
var stompClient = null;
// 设置 WebSocket 进入端点
var SOCKET_ENDPOINT = "/boot/semiautomatic/websocket";
// 设置订阅消息的请求前缀
var SUBSCRIBE_PREFIX = "/boot/semiautomatic/topic";
// 设置订阅消息的请求地址
var SUBSCRIBE = "/boot/semiautomatic/topic/taskinfo";
// 设置服务器端点，访问服务器中哪个接口
var SEND_ENDPOINT = "/app/semiautomatic/getTaskInfo";



/* 进行连接 */
function connect(craneId) {
    // 设置 SOCKET
    var socket = new SockJS(SOCKET_ENDPOINT);
    // 配置 STOMP 客户端
    stompClient = Stomp.over(socket);
//禁用debug模式
    stompClient.debug = null
    // STOMP 客户端连接
    stompClient.connect({}, function (frame) {
        getSubSCRIBE(craneId);
    });
}

/* 订阅信息 */
function subscribeSocket(){
    // 执行订阅消息
    stompClient.subscribe(SUBSCRIBE, function (responseBody) {
        var receiveMessage = JSON.parse(responseBody.body);
        switch (receiveMessage.infoType){
            case "taskProgress":
                $("#taskprogress").attr("lay-percent", (String(receiveMessage.detail)+"%"));
                break;
            case "taskName":
                $("#taskName").text(receiveMessage.detail);
                break;
            case "remain":
                $("#remaintask").text(receiveMessage.detail);
                break;
            case "total":
                $("#total").text(receiveMessage.detail);
                break;
            case "craneLocation":
                var craneLocationMap = JSON.parse(receiveMessage.detail);
                $("#grablocation").text("x："+craneLocationMap["grabX"]+"     "+"y："+craneLocationMap["grabY"]+"z："+craneLocationMap["grabZ"]);
                $("#nowlocation").text("x："+craneLocationMap["realtimeX"]+"     "+"y："+craneLocationMap["realtimeY"]+"z："+craneLocationMap["realtimeZ"]);
                $("#targetlocation").text("x："+craneLocationMap["unwindX"]+"     "+"y："+craneLocationMap["unwindY"]+"z："+craneLocationMap["unwindZ"]);
                break;
            default:
                console("Error Messsage！");
        }
    });
}

/* 断开连接 */
function disconnect() {
    stompClient.disconnect(function() {
        alert("断开连接");
    });
}

/* 发送消息并指定目标地址（这里设置的目标地址为自身订阅消息的地址，当然也可以设置为其它地址） */
function sendMessageNoParameter() {
    // 设置发送的内容
    var sendContent = $("#content").val();
    // 设置待发送的消息内容
    var message = '{"destination": "' + SUBSCRIBE + '", "content": "' + sendContent + '"}';
    // 发送消息
    console.log(SEND_ENDPOINT);
    stompClient.send(SEND_ENDPOINT, {}, message);
}

//发送消息获取任务状态
function sendMessageForGetTastInfo(craneId){
    // console.log(craneId);
    var message = getMessage(craneId);
    //发送消息
    stompClient.send(SEND_ENDPOINT, {}, message);
}

function getMessage(craneId){
    var GET_TASK_INFO_PREFIX = "getTaskInfoCrane";
    var message;

    message = '{"destination": "' + SUBSCRIBE + '", "content": "' + GET_TASK_INFO_PREFIX + craneId.toString()+ '"}';
    return message;

}

function getSubSCRIBE(craneId){
    SUBSCRIBE = SUBSCRIBE+craneId;
}